package ext.tianma.bom.service.sqe;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.bom.service.SelectPartService;
import ext.tianma.bom.util.GenericUtil;
import wt.access.NotAuthorizedException;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.iba.definition.IBADefinitionException;
import wt.iba.definition.litedefinition.AttributeDefDefaultView;
import wt.iba.definition.service.IBADefinitionHelper;
import wt.iba.value.DefaultAttributeContainer;
import wt.iba.value.IBAHolder;
import wt.iba.value.IBAValueUtility;
import wt.iba.value.StringValue;
import wt.iba.value.litevalue.AbstractValueView;
import wt.iba.value.litevalue.StringValueDefaultView;
import wt.iba.value.service.IBAValueHelper;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.OneOffVersionIdentifier;
import wt.vc.OneOffVersionInfo;
import wt.vc.VersionControlHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

public class SQEPartHelper {

	private static Locale LOCALE = Locale.CHINA;
	private static final Logger log = LogR.getLogger(SQEPartHelper.class.getName());

	
	/**
	 * 返回成品的展示信息
	 * @param list
	 * @param array
	 * @return
	 */
	public static JSONArray setData(List<WTPart> list, JSONArray array) {

		String partDescription = "";
		String projectName = "";
		String projectNumber = "";

		for (int i = 0; i < list.size(); i++) {
			WTPart part = list.get(i);
			List<WTPart> list2 = getChildlist(part.getNumber(), part.getViewName());
			System.out.println("=====list2.size()========"+list2.size());
			if(list2.size() == 0) {
				continue;
			}
			
			try {
				System.out.println("------setData------");
				partDescription = getIBAStringValue(part, "partDescription");
				projectName = getIBAStringValue(part, "cn.tianma.projectName");
				projectNumber = getIBAStringValue(part, "cn.tianma.projectNumber");
				JSONObject object = new JSONObject();
				
				/*if (projectName == null) {
					object.put("partNumber", part.getNumber());
					object.put("partName", part.getName());
					object.put("viewName", part.getViewName());
					object.put("partDescription", partDescription);
					object.put("projectName", "");
					object.put("projectNumber", "");

					array.put(object);
				} else {*/
					object.put("partNumber", part.getNumber());
					object.put("partName", part.getName());
					object.put("viewName", part.getViewName());
					object.put("partDescription", partDescription);
					object.put("projectName", projectName);
					object.put("projectNumber", projectNumber);

					array.put(object);
				//}
			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return array;

	}

	
	/**
	 * 返回原材料的展示信息
	 * @param childlist
	 * @param array
	 * @return
	 * @throws Exception 
	 */
	public static JSONArray setData2(List<WTPart> childlist, JSONArray array) throws Exception {

		String specialMonitor = "";
		String partSupplier = "";
		String partDescription = "";
		String whetherPartRecognize = "";
		String partRecognize = "";
		String whetherValues = "";
		JSONObject obj = new JSONObject();
		WTPart part = null;

		try {
			obj.put("status", "success");
			System.out.println("------childlist.size()----" + childlist.size());
			// 返回零件的信息
			for (WTPart p : childlist) {
				part = getPart(p.getNumber(), "", "Design");
				JSONObject object = new JSONObject();
				//是否需要零件承认
				partRecognize = getIBAStringValue(part, "partRecognize");
				if(!"是".equals(partRecognize)) {
					continue;
				}
				//是否专显
				specialMonitor = getIBAStringValue(part, "specialMonitor");
				partSupplier = getIBAStringValue(part, "partSupplier");
				partDescription = getIBAStringValue(part, "partDescription");
				String url = SelectPartService.generateInfoPageURL(part);
				String numUrl = "<a target='_blank' href='"+url+"'>"+part.getNumber()+"</a>";
				String excelNum = part.getNumber();
				//是否已经样品承认
				whetherPartRecognize = getIBAStringValue(part, "whetherPartRecognize");
				if("是".equals(whetherPartRecognize)) {
					whetherValues = "已完成样品承认";
				} 
				if("正在审核".equals(whetherPartRecognize)) {
					whetherValues = "正在审核";
				} else {
					whetherValues = "未提交样品承认";
				}
				System.out.println("-----partNum:"+part.getNumber()+"--------part.getview:"+part.getViewName()+"-----partRecognize:"+partRecognize);
				
				object.put("excelNum", excelNum);
				object.put("partNumber", numUrl);
				object.put("partName", part.getName());
				object.put("partDescription", partDescription);
				object.put("specialMonitor", specialMonitor);
				object.put("partSupplier", partSupplier);
				object.put("whetherPartRecognize", whetherValues);
				array.put(object);
			}

		} catch (JSONException e) {
			log.error(e.getMessage(), e);
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return array;

	}

	
	/**
	 * 获取指定试图下的子料
	 * @param number
	 * @param view
	 * @return
	 */
	public static List<WTPart> getChildlist(String number, String view) {

		List<WTPart> list = getAllLatestVersionPart(number);
		// 找指定视图的BOM
		WTPart bompart = null;
		List<WTPart> childlist = new ArrayList<WTPart>();
		System.out.println("----------view-----------" + view);
		if (!isNullOrEmpty(view)) {
			try {
				bompart = GenericUtil.getPart(number, "", view);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			// 找BOM下的零件
			try {
				if (bompart != null) {
					childlist = getchildPart(bompart, childlist);
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
			System.out.println("===========viewNotNull  childlist 1==========" + childlist.size());
		} else {
			for (WTPart part1 : list) {
				childlist = getchildPart(part1, childlist);
			}
			System.out.println("===========viewNull  childlist 2 ==========" + childlist.size());
		}

		return childlist;
	}

	

	/**
	 * 获取关系中的部件
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static List<WTPart> getchildPart(WTPart part, List<WTPart> list) {
		try {
			QueryResult qs = WTPartHelper.service.getUsesWTPartMasters(part);
			while (qs.hasMoreElements()) {
				WTPartUsageLink link = (WTPartUsageLink) qs.nextElement();
				WTPartMaster master = (WTPartMaster) link.getRoleBObject();
				WTPart childpart = GenericUtil.getPart(master.getNumber(), "", part.getViewName());
				if (!list.contains(childpart) && childpart != null) {
					list.add(childpart);
				}
				if (childpart != null) {
					getchildPart(childpart, list);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}


	/**
	 * 根据部件编号获取所有最新小版本
	 * 
	 */
	public static ArrayList<WTPart> getAllLatestVersionPart(String number) {
		ArrayList<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = ext.tianma.bom.eco.BOMHelp.getPart(part.getNumber(), v, part.getView().getName());
				if (null != p) {
					continue;
				}
				String version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
				//System.out.println("----view:" + part.getViewName() + "===version:" + version + "<br>");
				//System.out.println("----proNum-----" + getIBAStringValue(part, "cn.tianma.projectNumber"));
				if (!list.contains(part)) {
					/*if (b == true) {
						System.out.println("-----true-----");
						if (getIBAStringValue(part, "cn.tianma.projectNumber").equals(proNum)) {
							list.add(part);
						}
					} else {*/
						//System.out.println("-----false-----");
						list.add(part);
					//}

				}
			}
		} catch (Exception e) {

		}
		return list;

	}



	/**
	 * 根据对象属性名获取对应的属性值
	 * 
	 * @param obj
	 * @param ibaName
	 * @return
	 * @throws WTException
	 */
	public static String getIBAStringValue(WTObject obj, String ibaName) throws WTException {

		String value = null;
		String ibaClass = "wt.iba.definition.StringDefinition";

		try {
			if (obj instanceof IBAHolder) {
				IBAHolder ibaholder = (IBAHolder) obj;
				DefaultAttributeContainer defaultattributecontainer = getContainer(ibaholder);

				if (defaultattributecontainer != null) {

					AbstractValueView avv = getIBAValueView(defaultattributecontainer, ibaName, ibaClass);
					if (avv != null) {
						value = ((StringValueDefaultView) avv).getValue();
						wt.iba.value.litevalue.UnitValueDefaultView s;

					} else {
						value = "";
					}
				}
			}
		} catch (RemoteException e) {

			e.printStackTrace();
		}

		return value;
	}

	public static DefaultAttributeContainer getContainer(IBAHolder ibaholder) throws WTException, RemoteException {

		ibaholder = IBAValueHelper.service.refreshAttributeContainer(ibaholder, null, LOCALE, null);
		DefaultAttributeContainer defaultattributecontainer = (DefaultAttributeContainer) ibaholder
				.getAttributeContainer();

		return defaultattributecontainer;
	}

	public static AbstractValueView getIBAValueView(DefaultAttributeContainer dac, String ibaName, String ibaClass)
			throws WTException {

		AbstractValueView aabstractvalueview[] = null;
		AbstractValueView avv = null;

		aabstractvalueview = dac.getAttributeValues();
		for (int j = 0; j < aabstractvalueview.length; j++) {
			String thisIBAName = aabstractvalueview[j].getDefinition().getName();
			String thisIBAValue = IBAValueUtility.getLocalizedIBAValueDisplayString(aabstractvalueview[j], LOCALE);
			String thisIBAClass = (aabstractvalueview[j].getDefinition()).getAttributeDefinitionClassName();

			if (thisIBAName.equals(ibaName) && thisIBAClass.equals(ibaClass)) {
				avv = aabstractvalueview[j];

				break;
			}
		}

		return avv;
	}

	/**
	 * 空或者NULL值时返回true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str.equals("NULL"));
	}

	/**
	 * 根据属性名和属性值获取物料
	 * 
	 * @param ibaName
	 * @param ibaValue
	 * @return
	 * @throws IBADefinitionException
	 * @throws NotAuthorizedException
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static ArrayList<WTPart> searchIBA(String ibaName, String ibaValue)
			throws IBADefinitionException, NotAuthorizedException, RemoteException, WTException {
		ArrayList<WTPart> partList = new ArrayList<WTPart>();
		AttributeDefDefaultView addv = IBADefinitionHelper.service.getAttributeDefDefaultViewByPath(ibaName);

		QuerySpec qs = new QuerySpec(wt.iba.value.StringValue.class);
//			 int ndx = qs.appendClassList(wt.iba.value.StringValue.class, false);

		int ndx = 0;
		long ibaDefId = addv.getObjectID().getId();
		qs.appendWhere(
				new SearchCondition(wt.iba.value.StringValue.class, wt.iba.value.StringValue.DEFINITION_REFERENCE + "."
						+ ObjectReference.KEY + "." + ObjectIdentifier.ID, SearchCondition.EQUAL, ibaDefId),
				new int[] { ndx });
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(wt.iba.value.StringValue.class, wt.iba.value.StringValue.VALUE,
				SearchCondition.EQUAL, ibaValue.toUpperCase()), new int[] { ndx });
		System.out.println("----qs----" + qs.toString());
		QueryResult qr = PersistenceHelper.manager.find(qs);
		//qr=new LatestConfigSpec().process(qr);
		while (qr.hasMoreElements()) {
			StringValue pp = (StringValue) qr.nextElement();
//		    	 Debug.P(pp.getType());
//		    	Persistable  p = sv.getIBAHolderReference().getObject();
			WTPart part = (WTPart) pp.getIBAHolderReference().getObject();
			//判断part是否为最新版本
			if(part!=null && part.isLatestIteration()) {
				partList.add(part);
			}
		}
		return partList;
	}

	
	/**
	 * 获取供应商为指定值的物料（模糊查询）
	 * @param ibaName
	 * @param ibaValue
	 * @return
	 * @throws IBADefinitionException
	 * @throws NotAuthorizedException
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static ArrayList<WTPart> searchPartSupplier(String ibaName, String ibaValue)
			throws IBADefinitionException, NotAuthorizedException, RemoteException, WTException {
		ArrayList<WTPart> partList = new ArrayList<WTPart>();
		AttributeDefDefaultView addv = IBADefinitionHelper.service.getAttributeDefDefaultViewByPath(ibaName);

		QuerySpec qs = new QuerySpec();
		int partIndex = qs.appendClassList(WTPart.class, true);
		int valueIndex = qs.appendClassList(StringValue.class, false);
		//int viewIndex = qs.appendClassList(View.class, false);
//			 int ndx = qs.appendClassList(wt.iba.value.StringValue.class, false);
		View view = ViewHelper.service.getView("Design");
		//int ndx = 0;
		long ibaDefId = addv.getObjectID().getId();
		qs.appendWhere(
				new SearchCondition(StringValue.class, StringValue.DEFINITION_REFERENCE + "."
						+ ObjectReference.KEY + "." + ObjectIdentifier.ID, SearchCondition.EQUAL, ibaDefId),
				new int[] { valueIndex });
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(StringValue.class, StringValue.VALUE,
				SearchCondition.LIKE, "%"+ibaValue.toUpperCase()+"%"), new int[] { valueIndex });
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(WTPart.class, "view.key.id",
				SearchCondition.EQUAL, view.getPersistInfo().getObjectIdentifier().getId()));
		qs.appendAnd();
	    qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"),
	        SearchCondition.EQUAL, new KeywordExpression("1")));
	    qs.appendAnd();
	    qs.appendWhere(new SearchCondition(new KeywordExpression("A0.Ida2a2"),
	        SearchCondition.EQUAL, new KeywordExpression("A1.Ida3a4")));
	    
	    
		System.out.println("----qs----" + qs.toString());
		QueryResult qr = PersistenceHelper.manager.find(qs);
		System.out.println("----qr.size----" + qr.size());
		//qr=new LatestConfigSpec().process(qr);
		while (qr.hasMoreElements()) {
			/*StringValue pp = (StringValue) qr.nextElement();
			WTPart part = (WTPart) pp.getIBAHolderReference().getObject();
			String view = part.getViewName();
			if((part!=null && part.isLatestIteration()) && ("Design".equals(view))) {
				partList.add(part);
			}*/
			Object obj[] = (Object[])qr.nextElement();
  	      if(obj[0] instanceof WTPart){
  	    	WTPart doc = (WTPart) obj[0];
					partList.add(doc);
				}
		}
		return partList;
	}

	/**
	 * list去重
	 * @param list
	 * @return
	 */
	public static ArrayList<WTPart> removeDuplicate(ArrayList<WTPart> list) {

		HashSet<WTPart> h = new HashSet<WTPart>(list);
		list.clear();
		list.addAll(h);
		return list;
	}
	
	/**
	 * 根据编号 版本 视图返回部件
	 * @param num
	 * @param ver
	 * @param viewName
	 * @return
	 * @throws Exception
	 */
	public static WTPart getPart(String num, String ver, String viewName)throws Exception {
    	if (viewName.equals(""))  viewName = "Design";
    	if ( num==null || num.equals("") ||  num.trim().equals("")) return null;
        View view = ViewHelper.service.getView(viewName);
        WTPart part = null;
        QuerySpec qs = new QuerySpec(WTPart.class);
        SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER,SearchCondition.EQUAL, num);
        qs.appendWhere(sc);
        sc = new SearchCondition(WTPart.class, "view.key.id",SearchCondition.EQUAL, view.getPersistInfo().getObjectIdentifier().getId());
        qs.appendAnd();
        qs.appendWhere(sc);
        if (!ver.equals("")) {
            qs.appendAnd();
            qs.appendWhere(new SearchCondition(new KeywordExpression("A0.versionida2versioninfo"), SearchCondition.EQUAL,new KeywordExpression("'" + ver + "'")));
        }
        qs.appendAnd();
        qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,new KeywordExpression("1")));
    
        qs.appendOrderBy(WTPart.class,"thePersistInfo.createStamp", true);
        QueryResult qr = PersistenceHelper.manager.find(qs);
       while (qr.hasMoreElements())
           { part = (WTPart) qr.nextElement();
              OneOffVersionInfo one=part.getOneOffVersionInfo();
              OneOffVersionIdentifier id=one.getIdentifier();
              String valueOneOff=id.getValue();
              if(valueOneOff==null)return part;                                    	 
          }
        return part;
    }

}
